package com.xucia.jsponic.datasource;

import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.BeanMap;

import com.xucia.jsponic.data.*;
import com.xucia.jsponic.datasource.*;

public abstract class BeanDataSource implements WritableDataSource {
	String id;
	public Object getFieldValue(LazyPropertyId valueId) throws Exception {
		BeanMap beanMap = getBeanMap(valueId.subObjectId);
		Object value = beanMap.get(valueId.getField());
		String id = getIdForBean(value);
		if (id != null)
			return ObjectId.idForObject(this,id).getTarget();
		return value;
	}
	protected abstract Object getBeanForId(String id);
	protected abstract String getIdForBean(Object bean);
	protected BeanMap getBeanMap(String id) {
		return new BeanMap(getBeanForId(id));
	}
	public void mapObject(PersistableInitializer initializer, String objectId) throws Exception {
		Object bean = getBeanForId(objectId);
		if (bean instanceof List)
			initializer.initializeList(((List)bean).iterator());
		
		BeanMap beanMap = new BeanMap(bean);
		
		for (String key : (Set<String>) beanMap.keySet())
			initializer.setProperty(key, new LazyPropertyId(this,objectId,key));
		initializer.finished();
	}


	public String getId() {
		return id;
	}



	public void recordPropertyAddition(String objectId, String name, Object value) throws Exception {
		
	}
	public void recordPropertyChange(String objectId, String name, Object value) throws Exception {
		// TODO Auto-generated method stub
		
	}
	public void recordPropertyRemoval(String objectId, String name) throws Exception {
		// TODO Auto-generated method stub
		
	}
	public void recordListAdd(String objectId, Object value) throws Exception {
		
	}
	public void recordListRemoval(String objectId, Object value) throws Exception {
		// TODO Auto-generated method stub
		
	}	public void setId(String id) {
		this.id = id;
	}


	

}
